package cn.sxt.userscenter.common.util;

import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
/*
 * 王氏加密算法
 * */
@Component("encryptUtil")
public class EncryptUtil {
	  
	
	public String randStr(int length){
		//生成一个随机的字符串
		StringBuffer sb=new StringBuffer();
		Random random=new  Random();
		for(int i=0;i<length;i++){
			
			int randInt=random.nextInt(ConstatFinalUtil.ALLSTR.length());
			char ch=ConstatFinalUtil.ALLSTR.charAt(randInt);
			sb.append(ch);
		}
		return sb.toString();
	}
	
	//加密
	public String encode(String souStr){
		//密文的结构:	sha256$rand$sha256Hex(rand+souStr)	
		String digType="sha256";
		String spli="$";
		
		String rand=this.randStr(32);
		//加盐
		String jiami=DigestUtils.sha256Hex(rand+souStr);
			//返回密文									
		return digType+spli+rand+spli+jiami;
	}
	//传入明文souStr和加密后的字符串encodePass
	public static boolean decode(String souStr,String encodePass){
		String spli="$";
		String digType="sha256";
		//转义字符，识别$
		String []encode=encodePass.split("\\"+spli);
		String randStr=encode[1];
		
		//拆分后的密文的rand部分进行加盐算法
		String jiami= DigestUtils.sha256Hex(randStr+souStr);
		//重新组合成密文与原文加密后的内容进行比较
		String jiamiStr=digType+spli+randStr+spli+jiami;
		return encodePass.equalsIgnoreCase(jiamiStr);
	}
	public static void main(String[] args) {
		EncryptUtil encryptUtil=new EncryptUtil();
		System.out.println(encryptUtil.randStr(32));
		
		
		String sourPass="11111";
		String jiami=encryptUtil.encode(sourPass);
		System.out.println(jiami);
		
		boolean flag=decode(sourPass,jiami);
		System.out.println("--------------"+flag);
	}
}
